
import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import { useEffect, useRef, useState } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';

import NineImage from '../../components/NineImage';
import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import ProcessTitle from '../../components/processStep/processTitle';
import ProcessStatus from '../../components/processStep/processStatus';
import { CompleteButton, NextButton } from '../../components/processStep/processButton';
import { getUserProgressStepApi, setUserProgressStepStatusApi } from '../../api/myself';

import './index.scss';

/**
 * 用户学习时间页面 - 刷学时指南
 */
const UserStudyTimePage = () => {
  const firstLoadRef = useRef<boolean>(false);
  const [userStep, setUserStep] = useState<any>({
    id: 0, 
    name: "", 
    status: 0, 
    completed_time: "", 
    children: []
  });
  const { setCarSubjectStepProcessStatus } = useAppContext();
  const stepId = Taro.getCurrentInstance().router?.params?.stepId || '5';
  const subjectId = Taro.getCurrentInstance().router?.params?.tab || '1';
  const isSubject1 = stepId === '5' && subjectId == '1';
  const [showTextContent, setShowTextContent] = useState<string>('image');

  // 获取初始化信息
  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(Number(stepId));
      if(res.code === 200 && res.data.length == 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          completed_time: result.created_at,
          children: result.children?.split(',') || [],
        });
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '获取用户进度失败', icon: 'none' });
    }
  }

  const updateStepStatus = async () => {
    try {
      const res = await setUserStepStatusApi(Number(stepId), 1);
      if(res.code === 200) {
        setUserStep({
          ...userStep,
          status: 2
        });
        Taro.showToast({ title: '已完成学时查询~', icon: 'success' });
        setCarSubjectStepProcessStatus(Number(stepId), 1);
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '预约失败，请稍后重试~', icon: 'none' });
    }
  }

  const setUserStepStatusApi = async (stepId: number, status: number) => {
    return setUserProgressStepStatusApi(stepId, status);
  }

  const nextStep = () => {
    Taro.navigateTo({ url: `/pages/${isSubject1 ? 'user-subject1-appoint' : 'user-subject4-appoint'}/index?stepId=${stepId+1}&tab=${subjectId}` });
  }

  useEffect(() => {
    if(!stepId) return;
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
    }
  }, []);

  return (
    <View className="page-container study-time-container">
      <PageHeader title={isSubject1 ? "科目一刷学时" : "科目四刷学时"} />
      {userStep.completed_time && (
        <ProcessStatus title={isSubject1 ? "科目一学习" : "科目四学习"} createTime={userStep.completed_time} />
      )}

      <ScrollView className="study-time-content-container" scrollY>
        <View className="main-card">

          <ProcessTitle 
            content={isSubject1 ? "科目一刷学时" : "科目四刷学时"}
            showTextContent={showTextContent} 
            setShowTextContent={setShowTextContent} 
          />
    
          {showTextContent === 'text' && (
            <View className="study-time-steps">
              <View className="steps-list">
                <View className="step-item">
                  <Text className="step-time-number">1</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      {isSubject1 ? (
                        <>
                          <View>和教练/老师约好面签后，</View>
                          <View>下载<Text className='importance-text'>长三角车生活APP</Text></View>
                        </>
                      ) : (
                        <View>下载<Text className='importance-text'>长三角车生活APP</Text></View>
                      )}
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">2</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击<Text className='importance-text'>我的</Text></View>
                      <View>点击<Text className='importance-text'>登录/注册</Text></View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">3</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击<Text className='importance-text'>学员</Text></View>
                      <View>点击<Text className='importance-text'>理论学习</Text></View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">4</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击<Text className='importance-text'>我已知晓 确认进入学习</Text></View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">5</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击
                        <Text className='importance-text'>客服电话400*****</Text>
                      </View>
                      <View>支付费用，点击
                        <Text className='importance-text'>开始学习</Text>
                      </View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">6</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>
                        {isSubject1 ? (
                          <View>点击<Text className="importance-text">科目一理论计时课程</Text></View>
                          ) : (
                            <View>点击<Text className="importance-text">科目四理论计时课程</Text></View>
                        )}
                        </View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">7</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击
                        <Text className='importance-text'>视频</Text>
                      </View>
                      <View>点击
                        <Text className='importance-text'>签到</Text>
                        完成拍摄
                      </View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">8</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击<Text className='importance-text'>开始计时</Text></View>
                      <View className='orange-tag text-base'>注意每次计时不能低于一分钟</View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">9</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击<Text className='importance-text'>签退</Text></View>
                      <View>完成<Text className='importance-text'>拍摄</Text></View>
                      <View className='orange-tag text-base'>注意不能隔天签退</View>
                    </View>
                  </View>
                </View>

                <View className="step-item">
                  <Text className="step-time-number">10</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>点击<Text className='importance-text'>学习记录</Text></View>
                      <View>完成有效学时<Text className='importance-text'>{isSubject1 ? '480分钟' : '400分钟10学时'}</Text></View>
                    </View>
                  </View>
                </View>
              </View>
            </View>
          )}
          {showTextContent === 'image' && (
            <NineImage images={null} stepId={stepId}/>
          )}

          <View className="button-container">
            {userStep.status == 0 ? (
              <CompleteButton onClick={updateStepStatus} />
            ) : (
              <NextButton onClick={nextStep}/>
            )}
          </View>

          {/* 特别注意 */}
          {isSubject1 && (
            <View className="study-time-notice">
              <View className="notice-title">
                <MaterialIcons name="info" size={20} color="#e6a23c" className="mr-2" />
                <Text className="notice-title-text">特别注意</Text>
              </View>
              <View className="notice-content">
                <Text>因面签的驾校不同，位置不一样，具体选择哪个界面平台，请和教练或客服老师联系。</Text>
                <Text>每次请"签到"进，"签退"出，不要隔天签退。</Text>
                <Text>开放时间为早上5:00至晚上23:00，余下时间请不要进入。</Text>
                <Text>学习时请留意人脸识别，确保签退签到准确无误，以保证理论学时的有效性。</Text>
                <Text>每日学习上线为230分钟，多的时间为无效学时。</Text>
              </View>
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  );
};

export default UserStudyTimePage;